#include "SprCompound.h"
#include "../ResourceHolder.hpp"
#include "SprQuad.h"
#include <cassert>
#include <SFML/Graphics/RenderTarget.hpp>
#include <cmath>
#include <memory>
#include <iostream>

namespace sf
{
	class Texture;
}

SprCompound::SprCompound(const sf::Texture& tex) :mTexture(tex),
mSprites(), mVertices(sf::Quads, 4),
mSpriteManager("C://Users//spirogio//Documents//visual studio 2013//Projects//SFMLGame1//Debug//Media//Robothand//robotArm2.scml"),
mRootQuad(mSpriteManager.createQuadTree()),
accumulate(sf::Time::Zero),
mName("")
{
	collectVertices();
}

SprCompound::SprCompound() :mTexture(),
mSprites(), mVertices(sf::Quads, 4),
mSpriteManager("C://Users//spirogio//Documents//visual studio 2013//Projects//SFMLGame1//Debug//Media//Robothand//robotArm2.scml"),
mRootQuad(mSpriteManager.createQuadTree()),
accumulate(sf::Time::Zero),
mName("")
{
	collectVertices();
}


//SprCompound::SprCompound() :mSprites(), mVertices(), mTexture(){}

void SprCompound::collectSprites()
{
	mSprites.clear();
	mRootQuad->getSprites(mSprites);
}

void SprCompound::collectVertices()
{
	collectSprites();
	assert(!mSprites.empty());
	mVertices.clear();
	std::sort(mSprites.begin(), mSprites.end(), 
		[](SprQuad* lh, SprQuad* rh){return lh->getDepth() < rh->getDepth(); });
	for (SprQuad* sQuad : mSprites)
	{
		for (std::size_t i = 0; i < 4; i++)
		{
			mVertices.append(sQuad->getWorldVertex(i));
		}
	}
}

void SprCompound::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
	states.transform *= getTransform();
	states.texture = &mTexture;
	target.draw(mVertices, states);
}

void SprCompound::setName(std::string name)
{
	mName = name;
}

std::string SprCompound::getName() const
{
	return mName;
}

void SprCompound::update(sf::Time dt)
{
	if (!mSprites.empty())
	{
		mSpriteManager.updateQuadTree(dt, mRootQuad);
		collectVertices();
	}
}

void SprCompound::setTexture(const sf::Texture& tex)
{
	mTexture = tex;
}

void SprCompound::setAnimation(int i)
{
	mSpriteManager.setAnimation(i);
}

